/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers;

import Controllers.utils.HibernateUtil;
import Controllers.utils.URLUtils;
import DAO.CommandeManager;
import DAO.LigneCommandeManager;
import Model.*;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Anthares
 */
public class Order extends BaseServlet {
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     * <p/>
     * @param request  servlet request
     * @param response servlet response
     * <p/>
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException      if an I/O error occurs
     */
    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String locale = getLocaleString(request);
        HashMap<String, String> requestedRessource = URLUtils.getRequestedRessource(getServletContext(), request);
        String action = requestedRessource.get("action");

        if(action == null){
            dispatch("/confirmorder.jsp", request, response);
        } else {
            if(action.equals("confirm")){
                confirmAction(request, locale, response);
                dispatch("/basket", request, response);
            } else {
                handleError(404, request, response);
            }
        }
    }

    private void confirmAction(HttpServletRequest request, String locale, HttpServletResponse response) {
        HttpSession sess = request.getSession();
        ProductBasket basket = (ProductBasket) sess.getAttribute("basket");

        Commande com = new CommandeManager(HibernateUtil.getSessionFactory(), locale).createCommande(basket.getSum(), (Client) sess.getAttribute("user"));

        LigneCommandeManager lComMan = new LigneCommandeManager(HibernateUtil.getSessionFactory(), locale);
        HashMap<Integer, BasketLine> lines = basket.getLines();
        for(BasketLine basketLine : lines.values()){
            lComMan.createAndInsertLigneCommande(com, basketLine.getProduct(), basketLine.getQuantity(), basketLine.getProduct().getReducedPrice());
        }
        basket.clear();
    }
}
